import router, { setIsInitAppData } from "/@/router";
import { Module } from "vuex";
import { RootState } from "/@/store";
import { LoginParams, login } from "/@/api/user";
import { buildShortUUID } from "/@/utils/uuid";
import authCache from "/@/utils/cache/authCache";
import { useI18n } from "/@/locales/useI18n";
import { message } from "ant-design-vue";

export interface UserState {
  username: string;
  name: string;
  captchaKey: string;
  userId: number | null | string;
}

const user: Module<UserState, RootState> = {
  namespaced: true,
  state: () => ({
    username: "",
    name: "",
    captchaKey: "",
    userId: null,
  }),
  mutations: {
    setUserInfo(state, payload) {
      state.name = payload.name;
      state.userId = payload.userId;
    },
    updateCaptchaKey(state) {
      state.captchaKey = buildShortUUID();
    },
  },
  actions: {
    async login({ dispatch }, params: LoginParams) {
      const rememberMe = params.rememberMe;
      delete params.rememberMe;
      const result = await login(params);
      if (!result) return null;
      if (rememberMe) {
        authCache.setRemUserInfo({
          username: params.username,
          password: params.password,
        });
      } else {
        authCache.setRemUserInfo(null);
      }
      authCache.setUserInfo({
        userId: -1,
        username: params.username,
        name: "unknow",
      });
      authCache.setToken(result.token as string);
      const appData = await dispatch("menu/getApplicationsByCurTenant", null, { root: true });
      if (appData && appData.length > 0) {
        setIsInitAppData(true);
        router.push(appData[0].url);
      } else {
        const { t } = useI18n();
        message.error(appData ? t("common.noAppData") : t("common.errAppData"));
      }
      return result;
    },
  },
};
export default user;
